package com.jeecg.p3.system.poster.service;

import com.jeecg.p3.base.util.ComCode;
import com.jeecg.p3.base.util.DataGrid;
import com.jeecg.p3.base.util.DateUtil;
import com.jeecg.p3.base.util.StringUtils;
import com.jeecg.p3.system.poster.dao.ExamAnswerDao;
import com.jeecg.p3.system.poster.dao.ExamPaperDao;
import com.jeecg.p3.system.poster.dao.ExamQuestionBankDao;
import com.jeecg.p3.system.poster.entity.ExamAnswer;
import com.jeecg.p3.system.poster.entity.ExamPaper;
import com.jeecg.p3.system.poster.entity.ExamQuestionBank;
import com.jeecg.p3.system.util.UuidUtils;
import com.jeecg.p3.system.vo.LoginUser;
import org.jeecgframework.p3.core.common.utils.AjaxJson;
import org.jeecgframework.p3.core.utils.common.PageList;
import org.jeecgframework.p3.core.utils.common.PageQuery;
import org.jeecgframework.p3.core.utils.common.PageQueryWrapper;
import org.jeecgframework.p3.core.utils.common.Pagenation;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 *
 * @ClassName: ExamPaperService
 * @Description: TODO 试题数据处理层
 * @author: zhangxiao
 * @date: 2021年1月10日 下午7:29:38
 */
@Service
public class ExamPaperService {
    @Resource
    private ExamPaperDao dao;
    @Resource
    private ExamAnswerDao answerDao;

    /**
     * 根据试题id查询试题及试题答案结果
     * @param paperId
     * @return
     */
    public ExamPaper findPaperAndAnswerById(String paperId) {
        ExamPaper examPaper = dao.get(paperId);
        ExamAnswer param = new ExamAnswer();
        param.setExamPaperId(paperId);
        List<ExamAnswer> answers = answerDao.findByParam(param);//根据试卷id查询试卷答案列表
        examPaper.setAnswerList(answers);
        return examPaper;
    }

    /**
     * 分页查询
     * @param pageQuery
     * @return
     */
    public PageList<ExamPaper> queryPageList(PageQuery<ExamPaper> pageQuery) {
        PageList<ExamPaper> result = new PageList<ExamPaper>();
        Integer itemCount = dao.count(pageQuery);
        PageQueryWrapper<ExamPaper> wrapper = new PageQueryWrapper<ExamPaper>(pageQuery.getPageNo(), pageQuery.getPageSize(),itemCount, pageQuery.getQuery());
        List<ExamPaper> list = dao.queryPageList(wrapper);
        Pagenation pagenation = new Pagenation(pageQuery.getPageNo(), itemCount, pageQuery.getPageSize());
        result.setPagenation(pagenation);
        result.setValues(list);
        return result;
    }

    /**
     * 分页查询
     * @param pageQuery
     * @return
     */
    public DataGrid pages(PageQuery<ExamPaper> pageQuery) {
        DataGrid grid = new DataGrid();
        Integer itemCount = dao.count(pageQuery);
        PageQueryWrapper<ExamPaper> wrapper = new PageQueryWrapper<ExamPaper>(pageQuery.getPageNo(), pageQuery.getPageSize(),itemCount, pageQuery.getQuery());
        List<ExamPaper> list = dao.queryPageList(wrapper);
        grid.setRows(list);
        grid.setTotal(itemCount.longValue());
        return grid;
    }

    /**
     * 根据传参获取数量
     * @param examPaper
     * @return
     */
    public Integer count(ExamPaper examPaper) {
        PageQuery<ExamPaper> pageQuery = new PageQuery<>();
        pageQuery.setQuery(examPaper);
        return dao.count(pageQuery);
    }

    /**
     * 新增信息
     * @param examPaper
     */
    @Transactional(rollbackFor = {Exception.class})
    public AjaxJson doAdd(ExamPaper examPaper, LoginUser user) {
        AjaxJson j = new AjaxJson();
        String date = DateUtil.dateToString(new Date());
        String time = DateUtil.dateToString(new Date(), "HH:mm:ss");
        List<ExamAnswer> answers = examPaper.getAnswerList();//前台提交过来的答案
        List<ExamAnswer> newAnswers = new ArrayList<>();//有效的答案
        ExamAnswer answer = new ExamAnswer();//正确答案
        Boolean isExist = false;//是否存在正确答案
        if(answers != null) {
            for (ExamAnswer ea: answers) {
                if(ea != null && answerIsNotNull(ea)) {
                    if(!isExist) {//还未有正确答案
                        if(ComCode.select.equals(ea.getIsCorrect())) {
                            isExist = true;
                            answer = ea;//正确答案赋值
                        }
                        newAnswers.add(ea);
                    } else {//已经有正确答案
                        if(ComCode.select.equals(ea.getIsCorrect())) {
                            j.setSuccess(false);
                            j.setMsg("只允许有一个正确答案！");
                            return j;
                        }
                        newAnswers.add(ea);
                    }
                }
            }
        }
        if(!isExist) {
            j.setSuccess(false);
            j.setMsg("没有正确答案，请检查！");
            return j;
        }
        if(newAnswers != null && newAnswers.size() > 0) {
            String examPaperId = UuidUtils.getId();
            for(ExamAnswer ea: newAnswers) {
                ea.setCreateDate(date);
                ea.setCreateTime(time);
                ea.setCreateUser(user.getId());
                ea.setStatus("1");
                ea.setExamPaperId(examPaperId);
                insertExamAnswer(ea);
            }
            examPaper.setCreateDate(date);
            examPaper.setCreateTime(time);
            examPaper.setCreateUser(user.getId());
            examPaper.setAnswer(answer);
            examPaper.setStatus("1");
            examPaper.setId(examPaperId);
            dao.insert(examPaper);
            j.setMsg("操作成功！");
            return j;
        } else {
            j.setSuccess(false);
            j.setMsg("请输入有效答案！");
            return j;
        }
    }

    /**
     * 判断答案为空
     * @param examAnswer
     * @return
     */
    public Boolean answerIsNotNull(ExamAnswer examAnswer) {
        if(StringUtils.isNotEmpty(examAnswer.getContext()) || (StringUtils.isNotEmpty(examAnswer.getIsCorrect()))) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 新增答案
     * @param examAnswer
     */
    public void insertExamAnswer(ExamAnswer examAnswer) {
        examAnswer.setId(UuidUtils.getId());
        answerDao.insert(examAnswer);
    }
    /**
     * 根据id查询信息
     * @param id
     * @return
     */
    public ExamPaper findById(String id) {
        return dao.get(id);
    }

    /**
     * 根据传参获取列表信息
     * @param examPaper
     * @return
     */
    public List<ExamPaper> findByParam(ExamPaper examPaper) {
        return dao.findByParam(examPaper);
    }

    /**
     * 编辑信息
     * @param examPaper
     */
    @Transactional(rollbackFor = {Exception.class})
    public AjaxJson doEdit(ExamPaper examPaper, LoginUser user) {
        AjaxJson j = new AjaxJson();
        String date = DateUtil.dateToString(new Date());
        String time = DateUtil.dateToString(new Date(), "HH:mm:ss");
        List<ExamAnswer> answers = examPaper.getAnswerList();//前台提交过来的答案
        List<ExamAnswer> newAnswers = new ArrayList<>();//有效的答案
        ExamAnswer answer = new ExamAnswer();//正确答案
        Boolean isExist = false;//是否存在正确答案
        if(answers != null) {
            for (ExamAnswer ea: answers) {
                if(ea != null && answerIsNotNull(ea)) {
                    if(!isExist) {//还未有正确答案
                        if(ComCode.select.equals(ea.getIsCorrect())) {
                            isExist = true;
                            answer = ea;//正确答案赋值
                        }
                        newAnswers.add(ea);
                    } else {//已经有正确答案
                        if(ComCode.select.equals(ea.getIsCorrect())) {
                            j.setSuccess(false);
                            j.setMsg("只允许有一个正确答案！");
                            return j;
                        }
                        newAnswers.add(ea);
                    }
                }
            }
        }
        if(!isExist) {
            j.setSuccess(false);
            j.setMsg("没有正确答案，请检查！");
            return j;
        }
        if(newAnswers != null && newAnswers.size() > 0) {
            answerDao.deleteByPaperId(examPaper.getId());//删除原有的答案
            for(ExamAnswer ea: newAnswers) {
                ea.setCreateDate(date);
                ea.setCreateTime(time);
                ea.setCreateUser(user.getId());
                ea.setStatus("1");
                ea.setExamPaperId(examPaper.getId());
                insertExamAnswer(ea);
            }
            examPaper.setUpdateDate(date);
            examPaper.setUpdateTime(time);
            examPaper.setUpdateUser(user.getId());
            examPaper.setAnswer(answer);
            examPaper.setStatus("1");
            dao.update(examPaper);
            j.setMsg("操作成功！");
            return j;
        } else {
            j.setSuccess(false);
            j.setMsg("请输入有效答案！");
            return j;
        }
    }

    /**
     * 删除信息
     * @param examPaper
     */
    @Transactional(rollbackFor = {Exception.class})
    public void doDelete(ExamPaper examPaper) {
        answerDao.deleteByPaperId(examPaper.getId());//删除答案
        examPaper.setStatus("0");
        dao.update(examPaper);//删除试题
    }
}
